package com.misic.cofig.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class CotrollerAop {

    @Pointcut("execution( * com.misic.wed.*.*(..))")
    public void LogAspect(){

    }
    @Before("LogAspect()")
    public void doBEfore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String  url=request.getRequestURI().toString();
        String ip=request.getRemoteAddr();
        String  classMethod=joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
        Object [] args=joinPoint.getArgs();
        Requesstlog requesstlog=new Requesstlog(url,ip,classMethod,args);//记录 前端控制器的请求路径
        //   ip地址  和  控制器的类名   传递的参数
        log.info("--------------Request--------------------"+requesstlog);

    }
    @After("LogAspect()")
    public void doAften(JoinPoint point) {

    }
    //@AfterReturning 在方法执行后返回一个结果后执行
  @AfterReturning(pointcut = "LogAspect()",returning="returnValue")
  public void log(JoinPoint point, Object returnValue) {
        System.out.println("模拟日志记录功能...");
        System.out.println("目标方法为：" +
                point.getSignature().getDeclaringTypeName() +
                "." + point.getSignature().getName());
        System.out.println("参数为：" +
                Arrays.toString(point.getArgs()));
        System.out.println("返回值为：" + returnValue);
     System.out.println("被织入的目标对象为：" + point.getTarget());
    }

    private class Requesstlog{
        private String url;
        private String  ip;
        private String  classMenrhod;
        private Object[] args;
        public Requesstlog(String url, String ip, String classMenrhod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMenrhod = classMenrhod;
            this.args = args;
        }
        @Override
        public String toString() {
            return "Requesstlog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMenrhod='" + classMenrhod + '\'' +

            ", args=" + Arrays.toString(args) +
                    '}';
        }}
}
